package com.bigpang.framework.example.cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author YongQiang
 * @Date 2021/7/13 15:59
 * @Version 1.0
 */
public class MyCglibBeanFactory {

    public static UserService createUservice(){
        final UserService userService = new UserService();
        final MyAspect myAspect = new MyAspect();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                myAspect.before();
                Object o1 = method.invoke(userService, objects);
                methodProxy.invokeSuper(o, objects);
                myAspect.after();
                return o1;
            }
        });
        UserService userService1 = (UserService) enhancer.create();
        return userService1;

    }
}
